package com.tianji.promotion.handle;

import cn.hutool.core.collection.CollUtil;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.enums.CouponStatus;
import com.tianji.promotion.enums.ObtainType;
import com.tianji.promotion.service.ICouponService;
import com.tianji.promotion.service.IExchangeCodeService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class IssueCouponHandle {
    private final ICouponService couponService;
    private final IExchangeCodeService codeService;

    @XxlJob("couponIssueJobHandler")
    public void couponIssueJobHandler(){
        log.debug("开始执行任务。。。。。");
        /**
         * 每20s定时发放优惠券
         */
        //1.查询数据库信息，哪些处于定时发放并且当前时间大于开始发放时间，且状态为待发放
        List<Coupon> coupons = couponService.lambdaQuery()
                .eq(Coupon::getStatus, CouponStatus.UN_ISSUE)
                .le(Coupon::getIssueBeginTime, LocalDateTime.now())
                .list();
        if(CollUtil.isNotEmpty(coupons)){
            //2.修改状态为进行中
            for (Coupon coupon : coupons) {
                CouponStatus firstStatus = coupon.getStatus();
                coupon.setStatus(CouponStatus.ISSUING);
                //2.1 生成对应兑换码
                if(coupon.getObtainWay() == ObtainType.ISSUE && firstStatus.equals(CouponStatus.DRAFT)){
                    codeService.generateExchangeCode(coupon);
                }
            }
        }
        /**
         * 定时结束发放优惠券
         */
        //1.查找到在进行时的优惠券并且结束发放时间是否小于当前时间 endtime < now
        List<Coupon> couponList = couponService.lambdaQuery()
                .eq(Coupon::getStatus, CouponStatus.ISSUING)
                .le(Coupon::getIssueEndTime, LocalDateTime.now())
                .list();
        //2.修改状态为已结束
        if(CollUtil.isNotEmpty(couponList)){
            for (Coupon coupon : couponList) {
                coupon.setStatus(CouponStatus.FINISHED);
            }
        }
        coupons.addAll(couponList);
        log.info("需要修改的优惠券集合：{}",coupons);
        couponService.saveOrUpdateBatch(coupons);
    }
}
